# import cProfile
# 性能分析https://www.cnblogs.com/Simon-xm/p/4171902.html

# 系统相关库
import sys
import os
import traceback
from queue import Queue
# UI相关库
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.uix.popup import Popup

# from kivy.uix.codeinput import CodeInput
# from pygments.lexers.python import PythonLexer
# codeinput = CodeInput(lexer=CythonLexer())

from kivy.properties import (
    NumericProperty, StringProperty, ReferenceListProperty, ObjectProperty, ListProperty
)
from kivy.core.text import LabelBase
LabelBase.register('Roboto','./res/fonts/msyh.ttf')# 注册字体
from kivy.graphics.texture import Texture
from kivy.clock import Clock

from kivy.core.window import Window

# 模块库
from ParseGesture import data2userCode
import PoseStream
import MatchGestrue
import globalvar as gv

import cv2

import main as maincli

from GestureScreen import GestureScreen
from EditorScreen import EditorScreen

class TopScreen(BoxLayout):
    # splitterright = ObjectProperty(None)
    eswidget = ObjectProperty(None)
    gswidget = ObjectProperty(None)
    def __init__(self, **kwargs):
        super(TopScreen, self).__init__(**kwargs)
        Window.size=(1000,600)
    def init(self,gs,es):
        self.gswidget.add_widget(gs)
        self.eswidget.add_widget(es)
    # 显示编辑框
    def show(self):
        # Window.size = (Window.size[0]*1.5, Window.size[1]) 
        self.eswidget.opacity=1
        self.eswidget.size_hint[0]=0.5
        self.gswidget.size_hint[0]=0.5
        self.gswidget.min_size=13

    # 隐藏编辑框
    def hind(self):
        # Window.size = (Window.size[0]/1.5, Window.size[1])  
        self.eswidget.opacity=0
        self.eswidget.size_hint[0]=0
        self.gswidget.size_hint[0]=None
        self.gswidget.size[0]=self.width+13
        self.gswidget.min_size=self.gswidget.size[0]


class GestureApp(App):
    def build_config(self, config):
        config.setdefaults('Basic', {
            'VIEW_HANDS': False,
            'VIEW_EDITOR': False
        })
        config.setdefaults('PoseStream', {
            'Min_detection_confidence': 0.5,
            'Min_tracking_confidence': 0.5,
            'Time_to_Sleep':1,
            'Count_to_Sleep': 10,
            'Count_to_Deque': 4,
            'Max_num_hands': 1
        })
        config.setdefaults('Editor', {
            'OPEN_FILES': ""
        })

    def build_settings(self, settings):
        jsondata = """
            [
                { "type": "title",
                "title": "基本设定" },

                { "type": "bool",
                "title": "是否显示影像",
                "desc": "",
                "section": "Basic",
                "key": "VIEW_HANDS" },

                { "type": "bool",
                "title": "是否显示编辑",
                "desc": "",
                "section": "Basic",
                "key": "VIEW_EDITOR" },

                { "type": "title",
                "title": "手部追踪参数" },

                { "type": "options",
                "title": "检测手数量",
                "desc": "",
                "section": "PoseStream",
                "key": "Max_num_hands",
                "options": ["1", "2", "3", "4"] },

                { "type": "options",
                "title": "检测置信度",
                "desc": "",
                "section": "PoseStream",
                "key": "Min_detection_confidence",
                "options": ["0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9"] },

                { "type": "options",
                "title": "追踪置信度",
                "desc": "",
                "section": "PoseStream",
                "key": "Min_tracking_confidence",
                "options": ["0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9"] },

                { "type": "numeric",
                "title": "休眠判定帧数",
                "desc": "",
                "section": "PoseStream",
                "key": "Count_to_Sleep" },

                { "type": "numeric",
                "title": "休眠秒数",
                "desc": "",
                "section": "PoseStream",
                "key": "Time_to_Sleep" },

                { "type": "numeric",
                "title": "防抖帧数量",
                "desc": "",
                "section": "PoseStream",
                "key": "Count_to_Deque" },

                { "type": "title",
                "title": "编辑器设定" },

                { "type": "string",
                "title": "默认打开",
                "desc": "",
                "section": "Editor",
                "key": "OPEN_FILES" }
            ]
            """
            
        settings.add_json_panel('Gesture APP',
            self.config, data=jsondata)

    def on_config_change(self, config, section, key, value):
        if config is self.config:
            if section=="PoseStream":
                PoseStream.changeConfig(key, value)
            elif section=="Basic":
                gv.changeConfig(key, value)
                if key=="VIEW_HANDS":
                    if value=='1':
                        self.gs.start()
                    else:
                        self.gs.stop()
                elif key=="VIEW_EDITOR":
                    if value=='1':
                        self.ts.show()
                    else:
                        self.ts.hind()

    def build(self):
        self.gs=GestureScreen()
        self.es=EditorScreen()
        self.ts=TopScreen()
        self.ts.init(gs=self.gs,es=self.es)
        self.es.init(config=self.config)
        sys.stdout=self.gs
        return self.ts

    def on_start(self):
        # self.profile = cProfile.Profile()
        # self.profile.enable()
        config_basic={
            'VIEW_HANDS': self.config.getboolean('Basic','VIEW_HANDS'),
            'VIEW_EDITOR': self.config.getboolean('Basic','VIEW_EDITOR')
        }
        gv.changeConfig(config_basic)
        for key, value in config_basic.items():
            if key=="VIEW_HANDS":
                if value:
                    self.gs.start()
            elif key=="VIEW_EDITOR":
                if value:
                    self.ts.show()
                else:
                    self.ts.hind()
                
        config_posestream={
            'Min_detection_confidence': \
                self.config.getfloat('PoseStream','Min_detection_confidence'),
            'Min_tracking_confidence': \
                self.config.getfloat('PoseStream','Min_tracking_confidence'),
            'Time_to_Sleep': self.config.getint('PoseStream','Time_to_Sleep'),
            'Count_to_Sleep': self.config.getint('PoseStream','Count_to_Sleep'),
            'Count_to_Deque': self.config.getint('PoseStream','Count_to_Deque'),
            'Max_num_hands': self.config.getint('PoseStream','Max_num_hands')
        }
        PoseStream.changeConfig(config_posestream)
        # config_editor={
        #     'OPEN_FILES': \
        #         self.config.get('Editor','OPEN_FILES')
        # }
        OPEN_FILES=self.config.get('Editor','OPEN_FILES')
        
        for filepath in OPEN_FILES.split(';'):
            if filepath.strip()!="":
                self.es.load(filepath)
        maincli.start()

    def on_stop(self):
        # self.profile.disable()
        # self.profile.dump_stats('myapp.profile')
        maincli.poses_q.put(maincli._sentinel)
        filepaths=self.es.spinner.values[2:]
        for filepath in filepaths:
            if filepath in self.es._modified_set:
                self.es.save(path=filepath, text=filepath)
        self.config.set('Editor','OPEN_FILES',';'.join(filepaths))
        self.config.write()
        
if __name__ == '__main__':
    GestureApp().run()
    
    
    